<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>

<body>
  <script>
    const nodes = [
      { id: 1, parentId: null },
      { id: 2, parentId: 1 },
      { id: 3, parentId: 1 },
      { id: 4, parentId: 2 },
      { id: 5, parentId: 3 },
      { id: 6, parentId: 3 },
      { id: 7, parentId: 4 },
      { id: 8, parentId: 4 },
    ];

    function arrayToTree (list) {
      const map = new Map(list.map((node) => [node.id, { ...node, children: [] }]));
      const root = map.get(list[0].id);
      dfs(root);

      function dfs (node) {
        console.log(node);
        if (node.children === undefined) {
          node.children = [];
        }

        for (const child of list) {
          if (child.parentId === node.id) {
            const childNode = map.get(child.id);
            dfs(childNode);
            node.children.push(childNode);
          }
        }
      }

      return root;
    }

    console.log(arrayToTree(nodes));

  </script>
</body>

</html>l